package Buffer;

import java.io.*;

public class CopyFoldersDemo {
    public static void main(String[] args) {
        // 数据源对象
        File srcFile =new File("C:\\迅雷云盘");
        File destFile = new File("C:\\新建文件夹");

        try {
            copyFolder(srcFile,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void copyFolder(File srcFile, File destFile) throws IOException{
        // 判断是否为目录
        if (srcFile.isDirectory()) {
            // 在目标源下创建一样的目录
            String srcName = srcFile.getName();
            File newFolder = new File(destFile, srcName);
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            //获取所有数组
            File[] files = srcFile.listFiles();

            for (File src : files
            ) {
                // 递归调用
                copyFolder(src, newFolder);
            }

        } else {
            //直接复制
            File newFile = new File(destFile, srcFile.getName());
            copyFile(srcFile,newFile);
        }
    }


    // 字节缓冲流复制文件
    private static void copyFile(File srcFile, File destFile) {

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile))) {


            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
